import { defineStore } from 'pinia';
import router from '@/router';
import { useUserStore } from './user';
import { asyncRouter } from '@/router/modules';
import { filterRoutesByRole, filterRoutesToMenus } from '@/router/helpers';
import { getMenuList } from '@/api/auth';
import { RouteRecordRaw } from 'vue-router';
import { storage } from '@/utils/storage';

interface IRouteState {
  /** 权限路由的模式(static|dynamic) */
  routeMode: ImportMetaEnv['VITE_ROUTE_MODE'];
  /** 是否初始化权限路由的生成 */
  isInitRoute: boolean;
  /** 菜单渲染数据 */
  menus: App.Menu[];
  /** 缓存的路由 */
  cacheList: string[];
  routingAuthorityDatas: any[];
  filterRoutesToMenus: any[];
  routes: any;
  currentMenudatas: object;
}

export const useRouteStore = defineStore({
  id: 'route',
  state: (): IRouteState => ({
    routeMode: import.meta.env.VITE_ROUTE_MODE,
    isInitRoute: false,
    menus: [],
    cacheList: ["User"],
    routingAuthorityDatas: [],
    filterRoutesToMenus: [],
    routes: [],
    currentMenudatas: {} //当前开启的菜单数据
  }),
  getters: {},
  actions: {
    /** 初始化权限路由 */
    initRoute() {
      this.setUserInfo();

      if (this.routeMode === 'static') {
        this.initStaticRoute();
        // this.initDynamicRoute();
      } else {
        this.initDynamicRoute();
      }
    },
    /** 静态权限路由 */
    initStaticRoute() {
      const userStore = useUserStore();
      this.routes = filterRoutesByRole(asyncRouter, userStore.userInfo.role);
      this.routes.forEach((route: RouteRecordRaw) => {
        route.children?.length ? router.addRoute(route) : router.addRoute('root', route);
      });
      // this.setMenus(menus);
      this.isInitRoute = true;
    },
    /** 获取菜单配置数据 */

    async setUserInfo() {
      let menu = await storage.get('menu') as string
      let data = JSON.parse(menu)
      if (!data) {
        const res = await getMenuList({});
        data = res.data
      }
      storage.set('isShowMsg', data?.menus.findIndex((item: any) => item.path == '/appointment') !== -1 ? '1' : '0');
      if (data.menus?.length) {
        const array: App.Menu[] = [];
        this.routingAuthorityDatas = data.menus;
        
        // this.routes.forEach(
        //   (v: { path: ''; meta: {} }) =>
        //     data?.menus.forEach((m: App.Menu) => {
        //       if (v && m?.path === v?.path) {
        //         console.log(m,v,'====================');
        //         m.meta = v.meta;
        //         array.push(m);
        //       }
        //     })
        // );
        data?.menus.forEach( (dataMenu:any) => {
          this.routes.forEach((route:any) => {
            if(route.path === dataMenu.path) {
              dataMenu.meta = route.meta
              array.push(dataMenu);
            }
          });
        });

        this.filterRoutesToMenus = filterRoutesToMenus(this.routes);
        this.setMenus(array);
      }
    },
    /** 动态权限路由 */
    async initDynamicRoute() { },

    /** 设置菜单 */
    setMenus(menus: App.Menu[]) {
      this.menus = menus;
      // const menuJson = JSON.stringify(menus)
      // storage.set('menu', menuJson);
    },
    /** 扁平化 */
    flatten(arr: any) {
      return arr.flat(Infinity);
    },
    /** 设置当前打开的菜单数据 */
    setCurrentMenudatas(key: string) {
      let myMenus:any = []
       this.flatten([this.menus, this.menus[9]?.children])
       this.menus.forEach(item=> {
        myMenus.push(item)
        if(item.children && item.children.length) {
          myMenus = [...myMenus, ...item.children]
        }
       })
      this.currentMenudatas = myMenus.filter((menuData: any) => menuData?.path === key)[0];
    }
  }
});
